package com.wuyou.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuyou.controller.AdvTypeController;
import com.wuyou.domain.Result;
import com.wuyou.domain.bo.AdvPayLogBO;
import com.wuyou.domain.bo.AdvertisingBO;
import com.wuyou.domain.po.AdvPayLog;
import com.wuyou.domain.po.AdvType;
import com.wuyou.domain.po.Advertising;
import com.wuyou.mapper.AdvPayLogMapper;
import com.wuyou.mapper.AdvTypeMapper;
import com.wuyou.mapper.AdvertisingMapper;
import com.wuyou.service.IAdvTypeService;
import com.wuyou.service.IAdvertisingService;
import com.wuyou.util.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘雷雨
 * @since 2022-09-29
 */
@Service
public class AdvertisingServiceImpl extends ServiceImpl<AdvertisingMapper, Advertising> implements IAdvertisingService {

    @Autowired
    private AdvertisingMapper advertisingMapper;

    @Autowired
    private AdvPayLogMapper advPayLogMapper;

    @Autowired
    private AdvTypeMapper advTypeMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IAdvTypeService advTypeService;

    @Override
    @Transactional
    public AdvPayLogBO addAdvertising(AdvertisingBO advertisingBO) {
        IdWorker idWorker = new IdWorker();
        //BO转换PO
        Advertising advertising = new Advertising();
        BeanUtils.copyProperties(advertisingBO,advertising);
        //生成订单号
        Long oderNum = idWorker.nextId();
        advertising.setOrderNum((oderNum.toString()));//交易订单号,
        //广告表添加数据
        advertisingMapper.insert(advertising);
        //广告订单表添加数据
        AdvPayLog advPayLog = new AdvPayLog()
                .setAdvPayId(idWorker.nextId())//订单ID
                .setTotalPrice(advertising.getTotalPrice())//实付金额
                .setAdvertisingId(advertising.getAdvertisingId())//广告主键ID
                .setUserId(advertising.getUserId())//用户ID
                .setOrderNum((oderNum.toString()));//交易订单号,
        advPayLogMapper.insert(advPayLog);
        //修改广告栏位信息
        advTypeService.updateAdvRegion(advertising.getAdvTypeId(),"1");
        //删除广告缓存
        redisTemplate.delete("advertising");
        return new AdvPayLogBO(advPayLog.getOrderNum(),advPayLog.getTotalPrice(),"就是玩");
    }

    @Override
    public Integer updateAdvertisingByOrderNum(Advertising advertising) {
        advertising.setStatus(1);//1 = 投放成功
        UpdateWrapper<Advertising> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_num",advertising.getOrderNum());
        return advertisingMapper.update(advertising,updateWrapper);
    }

    @Override
    @Transactional
    public List<AdvertisingBO> findAdvertisingList() {
        List<AdvertisingBO> advertisingBOS = new ArrayList<>();
        HashOperations<String, Object, Object> redisHash = redisTemplate.opsForHash();

        if (redisTemplate.hasKey("advertising")) {
            List<Object> advertising = redisHash.values("advertising");
            for (Object o : advertising) {
                String adv = o.toString();
                advertisingBOS.add(JSONUtil.toBean(adv,AdvertisingBO.class));
            }
            return advertisingBOS;
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("status",1);
        List<Advertising> advertisings = advertisingMapper.selectList(queryWrapper);
        for (Advertising advertising : advertisings) {
            long now = System.currentTimeMillis();
            //获取每个广告的结束时间
            long time = advertising.getEndTime().getTime();
            if (time <= now) {
                //超过投放时间 设置失效x
                advertising.setStatus(2); // 2 = 已失效
                advertisingMapper.updateById(advertising);
            }
            if (advertising.getStatus() == 1) { // 1 = 正常投放时间
                ZSetOperations<String, String> redisZset = redisTemplate.opsForZSet();
                redisHash.put("advertising",advertising.getAdvertisingId().toString(),
                        JSONUtil.toJsonStr(advertising));
                redisZset.add("advertising_score",advertising.getAdvertisingId().toString(),time);
                AdvertisingBO advertisingBO = new AdvertisingBO();
                BeanUtils.copyProperties(advertising,advertisingBO);
                advertisingBOS.add(advertisingBO);
            }
        }
        return advertisingBOS;
    }
}
